#!/usr/bin/python
# -*- coding: UTF-8 -*-

from copy import deepcopy
from distutils.log import Log
from email import utils
import json
import http.client  #修改引用的模块
import hashlib
from msilib import Table
from multiprocessing.dummy import Array
from operator import index, truediv
from tokenize import group
from turtle import st    #修改引用的模块
from urllib import parse
import random
from Log import Debug

appid = '20220829001324165' #你的appid
secretKey = 'owSrQDeWHGPvI0U1BUm8' #你的密钥
singleTranslteMaxCount = 3 #单个单词翻译失败次数的上限

class WordInformation:
    
    _reqCount = None
    _from = None
    _to = None
    _text = None
    _translateText = None
    _nextWorld = None
    def __init__(self, text:str,fromLanguage:str,toLanguage:str,nextWorld) -> None:
        self._reqCount = 0
        self._text = text
        self._from = fromLanguage
        self._to = toLanguage
        self._nextWorld = nextWorld

    def CanReq(self):
        if self._reqCount > singleTranslteMaxCount:
            return False
        self._reqCount += 1
        return True

    def GetText(self):
        return self._text

    def GetTranslateText(self):
        if None != self._translateText:
            return self._translateText
        return self._text

    def GetNext(self):
        return self._nextWorld

def Translater( worldInfo:WordInformation):
    if worldInfo == None:
        return
    Debug.Log(f"{worldInfo.GetText()} 正在翻译...")
    myurl = '/api/trans/vip/translate'
    q = worldInfo.GetText()
    fromLang = worldInfo._from
    toLang = worldInfo._to
    salt = random.randint(32768, 65536)

    sign = appid+q+str(salt)+secretKey
    m1 = hashlib.md5()
    m1.update(sign.encode("utf-8"))
    sign = m1.hexdigest()
    myurl = myurl+'?appid='+appid+'&q='+parse.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign
    httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
    httpClient.request('GET', myurl)
    response = httpClient.getresponse()
    #转码
    html = response.read().decode('utf-8')
    html = json.loads(html)

    if httpClient:
        httpClient.close()
    
    if "trans_result" in html:
        dst = html["trans_result"][0]["dst"]
        worldInfo._translateText = dst
        # Translater(worldInfo.GetNext())
    # else:
    #     if worldInfo.CanReq():
    #         Translater(worldInfo)
    #     else:
    #         Translater(worldInfo.GetNext())

def GetWorldInfoArrByTextArr( texts:Array,fromLanguage:str,toLanguage:str ):
    num = len(texts)
    worlds = []
    for i in range(num-1,0,-1):
        if i == num - 1:
            world = WordInformation(texts[i],fromLanguage,toLanguage,None)
            worlds.append(world)
        else:
            world = WordInformation(texts[i],fromLanguage,toLanguage,worlds[len(worlds)-1])
            worlds.append(world)
    return worlds

def Translation( needTranslateTexts:Array,fromLanguage:str,toLanguage:str ):
    worlds = GetWorldInfoArrByTextArr(needTranslateTexts,fromLanguage,toLanguage)
    
    Debug.Runtime("翻译用时: ")
    # 递推方式  next指针不为none 递归执行next
    # Translater(worlds[len(worlds)-1])
    # 迭代方式 
    for i in range(0,len(worlds)):
        Translater(worlds[i])
        if worlds[i].GetTranslateText() == None and worlds[i].CanReq():
            i -= 1
    Debug.Runtime("翻译用时: ")

    worlds.reverse()
    translateTexts = [ ]
    for world in worlds:
        translateTexts.append(world.GetTranslateText())
    return translateTexts,worlds




